package com.jumeng.server.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jumeng.entity.CourseEntity;
import com.jumeng.entity.OrderEntity;
import com.jumeng.entity.PromotionRelationEntity;
import com.jumeng.entity.WxUserEntity;
import com.jumeng.mapper.CourseMapper;
import com.jumeng.mapper.PromotionMapper;
import com.jumeng.mapper.WxUserMapper;
import com.jumeng.server.CourseService;
import com.jumeng.server.WxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.UUID;

@Service
public class WxUserServiceImpl extends ServiceImpl<WxUserMapper, WxUserEntity> implements WxUserService {

    @Autowired
    private WxUserMapper wxUserMapper;

    @Autowired
    private PromotionMapper promotionMapper;

    @Override
    public String getPromotionCode(String openId) {
        LambdaQueryWrapper<WxUserEntity> wrapper = com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery();
        wrapper.eq(WxUserEntity::getOpenId, openId);
        // 当前登陆人
        WxUserEntity wxUserEntity = wxUserMapper.selectOne(wrapper);
        if (wxUserEntity == null) {
            throw new RuntimeException();
        }
        String uuid = UUID.randomUUID().toString().replace("-", "");
        // 推广码
        String discountCode = uuid.substring(0, 8);
        PromotionRelationEntity promotionRelationEntity = new PromotionRelationEntity();
        promotionRelationEntity.setCode(uuid);
        promotionRelationEntity.setMasterPromotionAccount(openId);
        promotionRelationEntity.setMasterPromotionCode(discountCode);
        // 保存关联关系
        promotionMapper.insert(promotionRelationEntity);
        return discountCode;
    }

    @Override
    public Boolean fillInPromotionCode(String openId, String promotionCode) {
        LambdaQueryWrapper<PromotionRelationEntity> wrapper = com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery();
        wrapper.eq(PromotionRelationEntity::getMasterPromotionCode, promotionCode);
        wrapper.isNull(PromotionRelationEntity::getFillInPromotionAccount);
        // 根据推广码查询推广记录
        List<PromotionRelationEntity> promotionRelationEntities = promotionMapper.selectList(wrapper);
        Optional<PromotionRelationEntity> promotionRelationEntity = promotionRelationEntities.stream().findAny();
        if (promotionRelationEntity.isPresent()) {
            PromotionRelationEntity relationEntity = promotionRelationEntity.get();
            // 推广人OpenId是唯一的
            relationEntity.setFillInPromotionAccount(openId);
            promotionMapper.updateById(relationEntity);
            return true;
        }
        return false;


    }
}
